package com.santoker.user.service.service.biz.auth.impl;

import com.santoker.baseservice.ApiResponseCode;
import com.santoker.baseservice.util.BCrypt;
import com.santoker.baseservice.util.DateUtils;
import com.santoker.baseservice.util.FileUtil;
import com.santoker.baseservice.util.Generator;
import com.santoker.user.service.config.ConfigProperty;
import com.santoker.user.service.dto.vo.auth.LoginResponseVo;
import com.santoker.user.service.exception.CommonServiceException;
import com.santoker.user.service.model.AdminUser;
import com.santoker.user.service.model.User;
import com.santoker.user.service.service.common.IUserService;
import com.santoker.user.service.service.common.RedisService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AuthBaseServiceImpl {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ConfigProperty configProperty;

    /**
     * 获取登录信息
     *
     * @param user 用户信息
     * @param sid  设备ID
     * @param cid  设备标识ID
     * @return
     */
    protected LoginResponseVo getLoginAdminResponse(AdminUser user, String sid, String cid) {
        // 生成登录Token
        String token = Generator.generateToken(user.getId(), user.getAccount(), user.getPassword(), sid);

        // 存储 Token、用户信息 到 Redis 中
        redisService.saveAdminToken(user, token, cid, sid);

        LoginResponseVo loginResponseVo = LoginResponseVo.builder()
                .token(token)
                .account(user.getAccount())
                .mobile(user.getMobile())
                .email(user.getEmail())
                .nickName(user.getNickname())
                .id(user.getId())
                .sId(sid)
                .avatar(FileUtil.getUrl(user.getAvatar(), configProperty.fileDomain))
                .build();
        return loginResponseVo;
    }

    /**
     * 获取登录信息
     *
     * @param user 用户信息
     * @param sid  设备ID
     * @param cid  设备标识ID
     * @return
     */
    protected LoginResponseVo getLoginResponse(User user, String sid, String cid) {
        // 生成登录Token
        String token = Generator.generateToken(user.getId(), user.getAccount(), user.getPassword(), sid);

        // 存储 Token、用户信息 到 Redis 中
        redisService.saveToken(user, token, cid, sid);

        LoginResponseVo loginResponseVo = LoginResponseVo.builder()
                .token(token)
                .account(user.getAccount())
                .mobile(user.getMobile())
                .email(user.getEmail())
                .nickName(user.getNickname())
                .wxNickName(user.getWxNickname())
                .openid(user.getOpenid())
                .id(user.getId())
                .sId(sid)
                .avatar(FileUtil.getUrl(user.getAvatar(), configProperty.fileDomain))
                .build();
        return loginResponseVo;
    }

    /**
     * 更新用户
     *
     * @param account    账号
     * @param mobile     手机号
     * @param email      邮箱
     * @param openid     微信唯一标识
     * @param wxNickName 微信昵称
     * @param avatar     头像
     * @return
     */
    @Transactional
    public User updateUser(User user, String account, String mobile, String email, String openid,
                           String wxNickName, String avatar) {
        user.setUpdatedAt(DateUtils.getSecondTimestamp());
        user.setAccount(account);
        if (StringUtils.isNotEmpty(mobile)) {
            user.setMobile(mobile);
        }
        if (StringUtils.isNotEmpty(email)) {
            user.setEmail(email);
        }
        user.setOpenid(openid);
        user.setWxNickname(wxNickName);
        user.setNickname(wxNickName);
        user.setAvatar(FileUtil.getNoDomainUrl(avatar, configProperty.fileDomain));
        if (!iUserService.updateById(user)) {
            throw new CommonServiceException(ApiResponseCode.REGISTER_FAILURE);
        }
        return user;
    }

    /**
     * 注册新用户
     *
     * @param account    账号
     * @param password   未加密密码
     * @param mobile     手机号
     * @param email      邮箱
     * @param openid     微信唯一标识
     * @param nickName   昵称
     * @param wxNickName 微信昵称
     * @param avatar     头像
     * @return
     */
    @Transactional
    public User registerNewUser(String account, String password, String mobile, String email, String openid,
                                String nickName, String wxNickName, String avatar) {
        // 生成密码盐、密码加密
        String hashPassword = BCrypt.hashpw(password, BCrypt.gensalt());

        // 添加用户信息
        User user = new User();
        user.setAccount(account);
        user.setPassword(hashPassword);
        user.setMobile(mobile);
        user.setEmail(email);
        user.setOpenid(openid);
        user.setNickname(StringUtils.defaultString(nickName));
        user.setWxNickname(wxNickName);
        user.setAvatar(FileUtil.getNoDomainUrl(avatar, configProperty.fileDomain));
        user.setCreatedAt(DateUtils.getSecondTimestamp());
        if (!iUserService.save(user)) {
            throw new CommonServiceException(ApiResponseCode.REGISTER_FAILURE);
        }
        return user;
    }

    /**
     * 验证密码
     *
     * @param oldPassword 原密码
     * @param newPassword 新密码
     * @return
     */
    protected boolean verifyPassword(String oldPassword, String newPassword) {
        return StringUtils.isNotBlank(oldPassword) && BCrypt.checkpw(newPassword, oldPassword);
    }

}
